<script setup lang="ts" name="DeleteButton">
import { deleteThirdSystem, passwordVerify } from "@/api/modules/businessManagement/thirdPartyManagement";
import { ref, reactive } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";

const visible = ref<boolean>(false);
const loadingSubmit = ref<boolean>(false);
let timer = ref<any>(null);
let count = ref<number>(5);
const ruleFormRef = ref<FormInstance>();
const modalFormRule = reactive<FormRules>({
  password: [{ required: true, message: "内容不能为空", trigger: ["blur", "change"] }]
});
const modalForm = reactive<any>({
  password: ""
});
const props = defineProps({
  data: {
    type: Object,
    required: false,
    default: () => {
      id: "";
    }
  }
});
const emit = defineEmits<{
  submitHandle: [];
}>();
const open = () => {
  visible.value = true;
  clearInterval(timer.value);
  timer.value = setInterval(() => {
    count.value--;
    if (count.value < 0) {
      clearInterval(timer.value);
    }
  }, 1000);
};
const close = () => {
  visible.value = false;
  clearInterval(timer.value);
  count.value = 5;
  modalForm.password = "";
  loadingSubmit.value = false;
};
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    return new Promise(async (resolve, reject) => {
      if (valid) {
        const user: any = localStorage.getItem("sys-user");
        const form = {
          user_id: JSON.parse(user).userInfo.id,
          password: modalForm.password
        };
        loadingSubmit.value = true;
        try {
          const { data } = await passwordVerify(form);
          if (data && data["is_correct"]) {
            deleteOperation();
          } else {
            ElMessage.error("密码错误！");
            loadingSubmit.value = false;
          }
        } catch (error) {
          console.error(error);
          ElMessage.error("未知错误！");
          loadingSubmit.value = false;
        }
      } else {
        return reject(false);
      }
    });
  });
};
const deleteOperation = async () => {
  try {
    const res = await deleteThirdSystem(props.data.id);
    if (res) {
      ElMessage.success("删除成功");
      emit("submitHandle");
    }
  } catch (error: any) {
    console.error(error);
    let str = "";
    if (error.response && error.response.data && error.response.data.message) {
      str = error.response.data.message;
    }
    ElMessage.error("删除失败" + (str.length > 0 ? ": " + str : ""));
  }
  loadingSubmit.value = false;
  close();
};
</script>

<template>
  <el-button @click="open" class="third-party-ant-btn" style="margin-left: 0">
    <i class="ri-delete-bin-line"></i>
    <span><slot>删除</slot></span>
    <el-dialog v-model="visible" destroy-on-close width="450px">
      <template #header>
        <div class="my-header">
          <el-icon style="font-size: 24px; color: #ff8d1a">
            <WarningFilled />
          </el-icon>
          <span>删除确认</span>
        </div>
      </template>
      <div class="modal-delete">
        <div class="modal-delete-content">
          <!--          <span class="modal-delete-content-header-title">-->
          <!--            <span>!</span>-->
          <!--            <div>删除确认</div>-->
          <!--          </span>-->
          <div class="modal-delete-content-header-content">
            <div>删除所选云平台需要密码验证</div>
            <div class="red">删除操作会清理与该系统相关的全部数据，请谨慎操作</div>
          </div>
          <el-form
            ref="ruleFormRef"
            :model="modalForm"
            :rules="modalFormRule"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 15 }"
          >
            <el-form-item label="密码" prop="password">
              <el-input v-model="modalForm.password" placeholder="请输入密码" :max="255" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="modal-footer">
          <el-button @click.stop="close">取 消</el-button>
          <el-button type="primary" v-show="count >= 0" disabled>（ {{ count }} ）</el-button>
          <el-button type="primary" v-show="count < 0" :loading="loadingSubmit" @click.stop="submit(ruleFormRef)">
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-button>
</template>

<style scoped lang="scss">
:deep(.el-dialog) {
  text-align: left;
}
.modal-delete-content {
  .modal-delete-content-header-title {
    box-sizing: content-box;
    display: flex;
    margin-top: 8px;
    font-size: 16px;
    font-weight: bold;
    span {
      display: block;
      width: 24px;
      height: 24px;
      color: #ffffffff;
      border-radius: 12px;
    }
    div {
      margin-left: 16px;
    }
  }
  .modal-delete-content-header-content {
    margin-top: 12px;
    margin-bottom: 18px;
    margin-left: 40px;
  }
}
.red {
  margin-top: 8px;
  font-weight: bold;
  color: red;
}
.my-header {
  display: flex;
  align-items: center;
  span {
    margin-left: 16px;
    color: var(--el-text-color-primary);
  }
}
</style>
